package com.hksj.Intelligentmanagement.service;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hksj.Intelligentmanagement.config.FilePathProperties;
import com.hksj.Intelligentmanagement.dto.FolderDTO;
import com.hksj.Intelligentmanagement.entity.Folder;
import com.hksj.Intelligentmanagement.entity.Music;
import com.hksj.Intelligentmanagement.mapper.FolderMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * 歌单文件 服务类
 * @author chenxingqing
 */
@Service
public class FolderService extends ServiceImpl<FolderMapper, Folder> {
    @Autowired
    private MusicService musicService;
    @Autowired
    private FilePathProperties filePathProperties;

    public Folder createFolder(FolderDTO dto) {
        Folder folder = new Folder();
        BeanUtils.copyProperties(dto,folder);
        FileUtil.file(filePathProperties.getMusic() + "/" + dto.getName()).mkdirs();

        save(folder);
        return folder;
    }

    public void updateFolder(FolderDTO dto) {
        Folder folder = getById(dto.getId());
        String oldName = folder.getName();
        String newName = dto.getName();
        folder.setName(dto.getName());
        folder.setSeq(dto.getSeq());
        File newDir = FileUtil.file(filePathProperties.getMusic() + "/" + newName);
        FileUtil.file(filePathProperties.getMusic() + "/" + oldName).renameTo(newDir);

        updateById(folder);
    }

    public void deleteFolder(Long id) {
        Integer count = musicService.lambdaQuery().eq(Music::getFolderId, id).count();
        if (count > 0) {
            throw new RuntimeException("歌单下存在歌曲，无法删除");
        }
        Folder folder = getById(id);

        FileUtil.del(filePathProperties.getMusic() + "/" + folder.getName());

        removeById(id);
    }

    public List<Folder> listFolder() {
        List<Folder> list = lambdaQuery()
                .eq(Folder::getDelFlag, 0)
                .orderByAsc(Folder::getSeq)
                .list();
        return list;
    }

    public String getDirPath(Long id) {
        Folder folder = getById(id);
        return filePathProperties.getMusic() + "/" + folder.getName();
    }
}
